<!--
 * @description 多行输入表格
 * @author zhanghuan
 * @date 2022/11/8
 -->
<template>
  <div class="input-table">
    <el-table :data="list" stripe size="mini">
      <el-table-column
        v-for="(item, i) in column"
        :key="i"
        :prop="item.prop"
        :label="item.label"
      >
        <template slot-scope="scope">
          <el-input
            v-model="scope.row[item.prop]"
            size="mini"
            @change="onChange"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="60">
        <template slot-scope="scope">
          <i class="el-icon-delete" @click="onDel(scope.$index)" />
        </template>
      </el-table-column>
    </el-table>
    <div class="input-table-add-btn" @click="onAddRow">添加行</div>
  </div>
</template>

<script>
export default {
  name: 'InputTable',
  props: {
    value: {
      type: String,
      default: ''
    },
    column: {
      type: Array,
      default() {
        return [
          {
            prop: 'name',
            label: '名称'
          },
          {
            prop: 'code',
            label: '标识'
          }
        ]
      }
    }
  },
  data() {
    return {
      list: []
    }
  },
  watch: {
    value(val) {
      if (val) {
        this.list = JSON.parse(val)
      } else {
        this.list = []
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      if (this.value) {
        this.list = JSON.parse(this.value)
      } else {
        this.list = []
      }
    },
    /**
     * 校验
     */
    validate() {
      if (!this.list.length) return false
      // 有添加行，但是一个字段都没填
      const flag = this.list.every((x) => Object.entries(x).every((y) => !y[1]))
      if (flag) return false
      return true
    },
    /**
     * 组件
     */
    onChange() {
      if (this.validate()) {
        const val = JSON.stringify(this.list)
        this.$emit('input', val)
        this.$emit('change', val)
      } else {
        this.$emit('input', '')
        this.$emit('change', '')
      }
    },
    /**
     * 添加行
     */
    onAddRow() {
      const row = {}
      this.column.forEach((x) => {
        row[x.prop] = ''
      })
      this.list.push(row)
    },

    /**
     * 删除行
     */
    onDel(i) {
      this.list.splice(i, 1)
      this.onChange()
    }
  }
}
</script>

<style scoped lang="scss">
.input-table {
  overflow: hidden;
  border-radius: 4px;
  border: 1px solid #dcdfe6;

  /deep/ .el-table__empty-block {
    display: none !important;
  }

  .input-table-add-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;

    &:hover {
      color: #fff;
      background: #ff7474;
    }
  }

  .el-icon-delete {
    padding: 5px 10px;
    cursor: pointer;
    &:hover {
      color: #ff7474;
    }
  }
}
</style>
